//仓库开始：14：31

import {createStore,applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import logger from 'redux-logger'

import {InitState,Action} from '../types/index'

// 所有请求通过状态管理容器统一处理
const initState:InitState={
    list:[],
    ind:0,
    carList:[],
    sum:0,
    number:0,
    all:false
}

const reducer =(state=initState,action:Action)=>{
    switch (action.type) {
        case 'GET_LIST_DATA':
            state.list=action.list
            return {...state}
        case 'GET_CHANGE_IND':
            state.ind=action.index
            return {...state}
            // 15、实现加入购物车功能，购物车本地数据与接口数据合并
        case 'SET_ADD_CAR':
            let index = state.carList.findIndex(item=>item.id===action.id)
            if(index===-1){
                state.list.forEach(item=>{
                    item.children.forEach(it=>{
                        if(it.id===action.id){
                            state.carList.unshift(it)
                        }
                    })
                })
            }else{
                state.list.forEach(item=>{
                    item.children.forEach(it=>{
                        it.num++
                    })
                })
            }
            return {...state,carList:[...state.carList]}
            // 16、实现购物车商品计算、删除功能
        case 'SET_CAR_ALL':
            state.all=!state.all
            console.log(state.all);
            
            if(state.all===true){
                state.carList.forEach(item=>{
                    item.flag=!item.flag
                })
                
            }
            state.sum = state.carList.reduce((p,n)=>{
                    return p+=n.num*n.price
                },0)
            
            return {...state,all:state.all,sum:state.sum}
        // case '':
    
        //     return {...state}
        default:

            return {...state}
    }
}

export default createStore(reducer,applyMiddleware(thunk,logger))